<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.store_name" placeholder="店铺名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.user_name" placeholder="联系人名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.store_phone" placeholder="手机号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.staff_uid" placeholder="请选择绑定的配件业务员" clearable>
          <el-option v-for="item in storageList" :label="item.username" :value="item.user_id" :key="item.user_id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.rent_staff_uid" multiple placeholder="请选择绑定的租机业务员" clearable>
          <el-option v-for="item in rentSalesmanList" :label="item.username" :value="item.user_id" :key="item.user_id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" class="mb10">
        <el-select v-model.trim="searchCondition.province_id" placeholder="请选择省份" clearable @change="handleChangeProvince">
          <el-option v-for="item in provinceList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" class="mb10">
        <el-select v-model.trim="searchCondition.city_id" placeholder="请选择城市" clearable @change="handleChangeCity">
          <el-option v-for="item in cityList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" class="mb10">
        <el-select v-model.trim="searchCondition.district" placeholder="请选择地区" clearable>
          <el-option v-for="item in districtList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.without_revisit_days" placeholder="请输入多少天未回访门店" clearable><template #append>天</template></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.is_first_order" placeholder="首单是否出单" clearable>
          <el-option v-for="item in whetherStatue" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.without_order_days" placeholder="请输入多少天未出单门店" clearable><template #append>天</template></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.shop_level" placeholder="店铺等级" clearable>
          <el-option v-for="item in shopLevelList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.online_promotion" multiple placeholder="请选择线上推广" clearable>
          <el-option v-for="item in onlinePromotionList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.settle_in_interest_points" multiple placeholder="请选择入驻兴趣点" clearable>
          <el-option v-for="item in settleInInterestPointsList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.customer_acquisition_channel" multiple placeholder="请选择获客渠道" clearable>
          <el-option v-for="item in customerAcquisitionChannelList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.materials" multiple placeholder="请选择物料" clearable>
          <el-option v-for="item in materialsList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.customer_action" multiple placeholder="请选择客户动作" clearable>
          <el-option v-for="item in customerActionList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.contract_review" placeholder="合同状态" clearable>
          <el-option v-for="item in contractReviewStatus" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="店铺通过开始时间" @change="changeQueryDate" end-placeholder="店铺通过结束时间"> </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-space wrap class="mb20">
      <el-button type="primary" :icon="Download" :disabled="disabledbtn" v-permission="'export'" @click="handleDeriveExcel">导出excel</el-button>
    </el-space>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="store_name" label="店铺名称">
        <template #default="scope">
          <div class="ibDraggable">
            <div>店铺名称：{{ scope.row.store_name }}</div>
            <div>联系人：{{ scope.row.user_name }}</div>
            <div>手机号：{{ scope.row.store_phone }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="staff.username" label="业务员">
        <template #default="scope">
          <div class="ibDraggable" v-if="scope.row.contacts_name">
            <div>配件：{{ scope.row.contacts_name }}</div>
          </div>
          <div class="ibDraggable" v-else>
            <div>配件：店面</div>
          </div>
          <div class="ibDraggable" v-if="scope.row.rent_contacts_name">
            <div>租机：{{ scope.row.rent_contacts_name }}</div>
          </div>
          <div class="ibDraggable" v-else>
            <div>租机：店面</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="approved_order_count" label="总订单数" align="center"></el-table-column>
      <el-table-column prop="offline_ratio" label="离线率/%" align="center"></el-table-column>
      <el-table-column prop="overdue_amount_ratio" label="逾期率/%" align="center"></el-table-column>
      <el-table-column prop="shop_level" label="店铺等级" align="center"></el-table-column>
      <el-table-column prop="first_order_time" label="相关时间" width="260">
        <template #default="scope">
          <div class="ibDraggable">
            <div>首单时间：{{ handleVerifyFormatDate(scope.row.first_order_time) }}</div>
            <div>通过时间：{{ handleVerifyFormatDate(scope.row.store_time) }}</div>
            <div>最后回访时间：{{ handleVerifyFormatDate(scope.row.business_affair_last_record_time) }}</div>
            <div>最近出单时间：{{ handleVerifyFormatDate(scope.row.last_order_time) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="EditPen" @click="handleViewEdit(scope.row, 'edit')">编辑</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'affairsRecord'" @click="handleFollowVisitRecord(scope.row)">商务回访</el-button>
            <div v-permission="'updateContract'" v-show="![null, ''].includes(scope.row.esign_pdf)">
              <el-popconfirm placement="top" width="160" title="你确定要删除合同吗?" @confirm="handleDeleteContract(scope.row)">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除合同</el-button>
                </template>
              </el-popconfirm>
            </div>
            <el-dropdown>
              <span class="el-dropdown-link">
                更多操作<el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button type="primary" link :icon="View" class="w100-t-a-l" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
                  </el-dropdown-item>
                  <!-- TODO：el-dropdown-item中嵌套了el-popconfirm会有异常 -->
                  <!-- <el-dropdown-item v-if="![null, ''].includes(scope.row.esign_pdf)">
                    <div v-permission="'updateContract'">
                      <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="handleDeleteContract(scope.row)">
                        <template #reference>
                          <el-button link :icon="Delete" type="danger">删除</el-button>
                        </template>
                      </el-popconfirm>
                    </div>
                  </el-dropdown-item> -->
                  <el-dropdown-item v-if="![null, ''].includes(scope.row.esign_pdf)">
                    <el-button type="primary" link :icon="View" @click="handleViewContractInfo(scope.row.esign_pdf)">查看合同</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="primary" link icon="View" @click="handleToVisitLogInfo(scope.row)">拜访记录</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="primary" link icon="View" @click="handleToFollowVisitRecordInfo(scope.row)">商务记录</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="primary" link :icon="ChatDotSquare" @click="handleRemark(scope.row)">平台备注</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <!-- 平台备注弹出框 -->
    <RemarkDialog v-model:editVisible="remarkVisible" v-model:form="sellerRemarkForm" @handleSuccess="handleRemarkSuccess" />
  </div>
</template>

<script setup lang="ts">
import RemarkDialog from "@/components/user/storeManager/storeInfo/RemarkDialog.vue";
import { View, EditPen, Search, Refresh, ChatDotSquare, Delete, Download } from "@element-plus/icons-vue";
import { exportExcel, handleVerifyFormatDate } from "@/utils/utils";
import type { ViewMode, ViewModeFilter } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { IStaff } from "@/types/staff/staff";
import type { IRentStaff } from "@/types/staff/rentStaff";
import type { ISearchDeleteContract, ISearchStore, IStoreInfoList, IStoreRemark } from "@/types/storeManager/store";
import { getStoreExportInfo, getStoreInfo, putStoreContractInfo } from "@/utils/api/store";
import type { IRegion, ISearchRegion } from "@/types/redPacketMallManage/region";
import { getRegionInfo } from "@/utils/api/region";
import { IMG_URL } from "@/utils/config";
import router from "@/router";
interface Props {
  storageList: Array<IStaff>;
  rentSalesmanList: Array<IRentStaff>;
  whetherStatue: Array<IDictData>;
  contractReviewStatus: Array<IDictData>;
  shopLevelList: Array<IDictData>;
  onlinePromotionList: Array<IDictData>;
  settleInInterestPointsList: Array<IDictData>;
  customerAcquisitionChannelList: Array<IDictData>;
  materialsList: Array<IDictData>;
  customerActionList: Array<IDictData>;
  provinceList: Array<IRegion>;
}
const { storageList, rentSalesmanList, whetherStatue, contractReviewStatus, shopLevelList, onlinePromotionList, settleInInterestPointsList, customerAcquisitionChannelList, materialsList, customerActionList, provinceList } = defineProps<Props>();
/* 市 */
const cityList = ref<Array<IRegion>>([]);
/* 区 */
const districtList = ref<Array<IRegion>>([]);

const { disabledbtn, loading, toggleState } = useState();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleViewEdit: [id: number, code: ViewModeFilter];
  handleFollowVisitRecord: [id: number];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */

const total = ref(0);
const searchCondition = reactive<ISearchStore>({
  store_name: "",
  store_state: "",
  shop_level: "",
  settled_status: "",
  deposit: "",
  sort_by_store_settled: "",
  staff_uid: "",
  store_phone: "",
  user_name: "",
  contract_review: "",
  province_id: "",
  city_id: "",
  district: "",
  support_by_store: "",
  start_time: "",
  end_time: "",
  without_revisit_days: "",
  is_first_order: "",
  without_order_days: "",
  settle_in_interest_points: [],
  online_promotion: [],
  customer_acquisition_channel: [],
  materials: [],
  customer_action: [],
  rent_staff_uid: [],
  support_all_mobile: [],
  size: 10,
  current: 1
});
const queryDate = ref<Array<string>>([]);
const tableList = ref<Array<IStoreInfoList>>([]);

const remarkVisible = ref(false); /* 商家备注弹出框 */
const sellerRemarkForm = reactive<IStoreRemark>({
  id: 0,
  store_note: ""
});
onMounted(() => {
  getTableInfo();
});
/* 查询 创建时间更改事件 */
function changeQueryDate(data: number[]) {
  if (data !== null) {
    searchCondition.start_time = data[0] * 1000;
    searchCondition.end_time = data[1] * 1000;
  } else {
    searchCondition.start_time = "";
    searchCondition.end_time = "";
  }
}
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.store_name = "";
  searchCondition.store_state = "";
  searchCondition.shop_level = "";
  searchCondition.settled_status = "";
  searchCondition.deposit = "";
  searchCondition.sort_by_store_settled = "";
  searchCondition.staff_uid = "";
  searchCondition.store_phone = "";
  searchCondition.user_name = "";
  searchCondition.contract_review = "";
  searchCondition.province_id = "";
  searchCondition.city_id = "";
  searchCondition.district = "";
  searchCondition.support_by_store = "";
  searchCondition.start_time = "";
  searchCondition.end_time = "";
  searchCondition.without_revisit_days = "";
  searchCondition.is_first_order = "";
  searchCondition.without_order_days = "";
  searchCondition.rent_staff_uid = [];
  searchCondition.settle_in_interest_points = [];
  searchCondition.online_promotion = [];
  searchCondition.customer_acquisition_channel = [];
  searchCondition.materials = [];
  searchCondition.customer_action = [];
  searchCondition.support_all_mobile = [];
  searchCondition.current = 1;
  searchCondition.size = 10;
  queryDate.value = [];
  cityList.value = [];
  districtList.value = [];
  getTableInfo();
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getStoreInfo<IStoreInfoList, ISearchStore>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IStoreInfoList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IStoreInfoList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 批量删除 */
// function batchDelete() {
//   /* 获取选中的数据 */
//   let selection = multipleTableRef.value!.store.states.selection.value;
//   if (selection.length === 0) {
//     ElMessage.warning("请至少选择一条数据");
//     return;
//   }
//   let idArray = [];
//   for (const item of selection) {
//     idArray.push(item.id);
//   }
//   deleteInfo(idArray);
// }
// /* 删除后的信息 */
// function deleteInfo(idArray: Array<number>) {
//   toggleState(true);
//   deleteMallRedPacketPurchaseInfo({ idArray })
//     .then(() => {
//       /* 当删除成功后，删除对应选中的数据或单个数据 */
//       tableList.value = tableList.value.filter((item: IStoreInfoList) => !idArray.includes(item.id));
//       ElMessage.success(`成功删除了${idArray.length}条数据`);
//       multipleTableRef.value!.clearSelection();
//       total.value = total.value - idArray.length;
//     })
//     .catch((error: Error) => {
//       console.log(error);
//     })
//     .finally(() => {
//       toggleState(false);
//     });
// }

/* 选择省 */
function handleChangeProvince() {
  cityList.value = [];
  districtList.value = [];
  searchCondition.city_id = "";
  searchCondition.district = "";
  handleGetRegionInfo(+searchCondition.province_id, cityList);
}
/* 选择市 */
function handleChangeCity() {
  districtList.value = [];
  searchCondition.district = "";
  handleGetRegionInfo(+searchCondition.city_id, districtList);
}

/* 获取省市县信息 */
function handleGetRegionInfo(parent_id: number, list: Ref<IRegion[]>) {
  getRegionInfo<IRegion, ISearchRegion>({ parent_id })
    .then(res => {
      list.value = ([] as IRegion[]).concat(res.result);
    })
    .catch(() => {});
}

/* 删除合同信息 */
function handleDeleteContract(row: IStoreInfoList) {
  const contract_review = 3;
  putStoreContractInfo<unknown, ISearchDeleteContract>({
    id: row.id,
    contract_review
  })
    .then(res => {
      ElMessage.success(res.msg);
      const statusDict = contractReviewStatus.find((item: IDictData) => item.dictValue == contract_review + "");
      const item = tableList.value.find((item: IStoreInfoList) => item.id == row.id);
      if (statusDict && item) {
        item.contract_review = contract_review;
        item.contract_review_name = statusDict!.dictLabel;
        item.esign_pdf = "";
      }
    })
    .catch(() => {});
}

/* 跳转到商务回访记录tab */
function handleFollowVisitRecord(row: IStoreInfoList) {
  emit("handleFollowVisitRecord", row.id);
}

/* 查看合同 */
function handleViewContractInfo(url: string) {
  window.open(IMG_URL + url, "_blank");
}
/* 跳转到拜访记录页面 */
function handleToVisitLogInfo(row: IStoreInfoList) {
  router.push({
    name: "visitLogInfo",
    query: { store_id: row.id, store_name: row.store_name }
  });
}
/* 跳转到商务记录页面 */
function handleToFollowVisitRecordInfo(row: IStoreInfoList) {
  console.log(row);
  router.push({
    name: "followVisitRecordInfo",
    query: { store_id: row.id, store_name: row.store_name }
  });
}

/* 平台备注 */
function handleRemark(row: IStoreInfoList) {
  remarkVisible.value = true;
  sellerRemarkForm.id = row.id;
  sellerRemarkForm.store_note = row.store_note;
}
/* 平台备注成功回调 */
function handleRemarkSuccess() {
  const order = tableList.value.find(order => order.id == sellerRemarkForm.id);
  if (order) order.store_note = sellerRemarkForm.store_note;
  remarkVisible.value = false;
}

/* 导出文件 */
function handleDeriveExcel() {
  toggleState(true);
  getStoreExportInfo({
    ...searchCondition,
    time: new Date().getTime()
  })
    .then(res => {
      ElMessage.success("请稍后，正在下载中...");
      exportExcel(res, "店铺信息" + new Date().getTime());
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
